"""
handle message for user-related operations
"""

import json


def get_user_message_history(db, logger, data: dict):
    """
    获取两个用户之间的消息记录
    data: {
        "id_1": str, # 用户1的mac_addr(查询方)
        "id_2": str, # 用户2的mac_addr
    }
    """
    try:
        logger.info(f"Fetching message history between {data['id_1']} and {data['id_2']}")
        # 查询两个用户之间的消息记录
        user1 = db.get_one("User", {"mac_addr": data["id_1"]})
        user2 = db.get_one("User", {"mac_addr": data["id_2"]})
        name_map = {
            data["id_1"]: user1.get("name"),
            data["id_2"]: user2.get("name"),
        }

        # 消息可能是从mac_addr_1到mac_addr_2，也可能是从mac_addr_2到mac_addr_1
        messages = db.get_all(
            "Message",
            {
                "source": data["id_1"],
                "target": data["id_2"],
            },
            order_by="created_at DESC",
            limit=50,
        )

        # 获取反向消息（从mac_addr_2到mac_addr_1）
        messages_reverse = db.get_all(
            "Message", {"source": data["id_2"], "target": data["id_1"]}, order_by="created_at DESC", limit=50
        )

        # 合并所有消息
        history_messages = [{**item, "target_name": name_map[item["source"]]} for item in (messages + messages_reverse)]

        # 根据 file_id 补充文件信息
        for index, msg in enumerate(history_messages):
            file_id = msg.get("file_id")
            if file_id:
                file_info = db.get_one("File", {"id": file_id})
                if file_info:
                    history_messages[index]["file"] = file_info

        # 批量更新消息状态为已读
        db.update_many("Message", {"status": "read"}, {"source": data["id_2"], "target": data["id_1"]})

        # 按时间排序
        history_messages.sort(key=lambda x: x.get("created_at", ""), reverse=True)
        return history_messages

    except Exception as e:
        raise e


async def send_msg_to_user(db, logger, ws_manager, data: dict):
    """
    发送消息给目标用户
    data: {
        "source": str, # 发送方的mac_addr
        "target": str, # 接收方的mac_addr
        "context_type": str, # text, file,
        "context": any, # str, dict
    }
    """
    try:
        # 获取目标用户信息
        target_user = db.get_one("User", {"mac_addr": data["target"]})
        source_user = db.get_one("User", {"mac_addr": data["source"]})

        if target_user and source_user:
            msg_id = None
            if data.get("context_type") == "file":
                msg_id = db.insert_one(
                    "Message",
                    {
                        "source": data["source"],
                        "target": data["target"],
                        "context": "File",
                        "file_id": data.get("context", {}).get("file_id"),
                        "status": "unread",
                    },
                )
            else:
                msg_id = db.insert_one(
                    "Message",
                    {
                        "source": data["source"],
                        "target": data["target"],
                        "context": data["context"],
                        "status": "unread",
                    },
                )

            message_content = {
                "category": "message",
                "source": data["source"],
                "source_name": source_user["name"],
                "target": data["target"],
                "target_name": target_user["name"],
                "message_id": msg_id,
                "context_type": data.get("context_type"),
                "context": data.get("context"),
            }
            # send message to target
            if target_user["socket_id"] in ws_manager.active_connections:
                await ws_manager.active_connections[target_user["socket_id"]].send_text(
                    json.dumps(
                        message_content,
                        ensure_ascii=False,
                    )
                )
                logger.info(f"向用户 {data['target']} 发送信息：{message_content}")
            else:
                logger.info(f"用户 {data['target']} 未在线")
        else:
            logger.info(f"用户不存在, 发送失败")

    except Exception as e:
        raise e
